package com.wmz.picture.manager;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.RandomUtil;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.model.ciModel.persistence.ImageInfo;
import com.qcloud.cos.model.ciModel.persistence.OriginalInfo;
import com.wmz.picture.common.ResultUtils;
import com.wmz.picture.config.CosClientConfig;
import com.wmz.picture.exception.BusinessException;
import com.wmz.picture.exception.ErrorCode;
import com.wmz.picture.exception.ThrowUtils;
import com.wmz.picture.model.dto.file.UploadPictureResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @author lihechun
 * @version 1.0
 * @description: 通用文件上传服务
 * @date: 2024/12/17 20:59
 */
@Service
@Slf4j
@Deprecated // 已废弃，改为使用upload包的模板方法优化
public class FileManager {
    @Resource
    private CosClientConfig cosClientConfig;

    @Resource
    private CosManager cosManager;

    /**
     * 上传图片
     * @param multipartFile 文件
     * @param uploadPathPrefix  上传路径前缀
     * @return
     */

    public UploadPictureResult uploadPicture(MultipartFile multipartFile, String uploadPathPrefix) {
        // 校验图片
        validPicture(multipartFile);
        // 图片上传地址
        String uuid = RandomUtil.randomString(16);
        String originalFilename = multipartFile.getOriginalFilename();
        // 真正存储的文件名：yyyy-mm-dd_uuid.后缀
        String uploadFileName = String.format("%s_%s.%s", DateUtil.formatDate(new Date()),uuid,FileUtil.getSuffix(originalFilename));
        // 文件路径
        String uploadPath = String.format("/%s/%s", uploadPathPrefix,uploadFileName);
        // 临时文件
        File tempFile = null;
        try {
            // 创建临时文件
            tempFile = File.createTempFile(uploadPath, null);
            multipartFile.transferTo(tempFile);
            // 上传图片
            PutObjectResult putObjectResult = cosManager.putPictureObject(uploadPath, tempFile);
            // 原始图片信息
            ImageInfo imageInfo = putObjectResult.getCiUploadResult().getOriginalInfo().getImageInfo();
            UploadPictureResult uploadPictureResult = new UploadPictureResult();
            // 图片宽/高/宽高比
            int picWidth = imageInfo.getWidth();
            int picHeight = imageInfo.getHeight();
            double picScale = NumberUtil.round(picWidth * 1.0 / picHeight, 2).doubleValue();
            // 封装返回结果
            uploadPictureResult.setPicName(uploadFileName);
            uploadPictureResult.setPicSize(multipartFile.getSize());
            uploadPictureResult.setPicWidth(picWidth);
            uploadPictureResult.setPicHeight(picHeight);
            uploadPictureResult.setPicScale(picScale);
            uploadPictureResult.setUrl(cosClientConfig.getHost() + uploadPath);
            uploadPictureResult.setPicFormat(imageInfo.getFormat());
            uploadPictureResult.setPicSize(FileUtil.size(tempFile));
            return uploadPictureResult;
        } catch (Exception e) {
            log.error("图片上传到对象存储失败",e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "图片上传失败");
        } finally {
            // 删除临时文件
            this.deleteTempFile(tempFile);
        }
    }


    /**
     * 图片校验
     * @param multipartFile 图片
     */
    public void validPicture(MultipartFile multipartFile) {
        ThrowUtils.throwIf(multipartFile == null, ErrorCode.PARAMS_ERROR,"文件不能为空！");
        // 1.校验文件大小
        final long ONE_M = 1024 * 1024;
        ThrowUtils.throwIf(multipartFile.getSize() >  2 * ONE_M, ErrorCode.PARAMS_ERROR,"文件大小不能超过2MB！");
        // 2.校验文件后缀
        // 允许上传的后缀
        List<String> suffixList = Arrays.asList("jpeg", "jpg", "png","webp");
        // 待上传的文件后缀
        final String fileSuffix = FileUtil.getSuffix(multipartFile.getOriginalFilename());
        ThrowUtils.throwIf(!suffixList.contains(fileSuffix), ErrorCode.PARAMS_ERROR,"文件格式错误！");
    }
    /**
     * 删除临时文件
     * @param file  待删除的文件
     */
    public void deleteTempFile(File file) {
        if(file == null) {
            return;
        }
        // 删除临时文件
        boolean delete = file.delete();
        if(!delete) {
            log.error("file delete error,filepath = {}", file.getAbsolutePath());
        }
    }
}
